package com.sunny.openplatformutils;

import java.io.IOException;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 新浪微博工具类
 *
 * @date 2017年5月8日
 *
 * @author Sunny 
 *
 */
public class Weibo {
	private static HttpClient client = new HttpClient();
	private static String client_ID, client_Sercret, redirect_URI;
	private static final String baseURL = "https://api.weibo.com/2/";
	private static final String accessTokenURL = "https://api.weibo.com/oauth2/access_token";
	private static Logger logger = LoggerFactory.getLogger(Weibo.class);
	
	public static void init(String clientId, String clientSercret, String redirectUri) {
		client_ID = clientId;
		client_Sercret = clientSercret;
		redirect_URI = redirectUri;
	}
	
	public static String getAccessToken(String code) {
		try {
			PostMethod post = new PostMethod(accessTokenURL);
			NameValuePair[] params = {
					new NameValuePair("client_id", client_ID),
					new NameValuePair("client_secret", client_Sercret),
					new NameValuePair("grant_type", "authorization_code"),
					new NameValuePair("code", code),
					new NameValuePair("redirect_uri", redirect_URI)};
			
			post.addParameters(params);
			post.getParams().setContentCharset("UTF-8");
			client.executeMethod(post);
			if (post.getStatusCode() == 200) {
				return post.getResponseBodyAsString();
			}
			logger.error(post.getResponseBodyAsString());
		} catch (IOException e) {
			logger.error("", e);
		}
		return null;
	}
	
	public static String getUserInfo(String accessToken, String uid) {
		try {
			StringBuilder url = new StringBuilder(baseURL)
					.append("users/show.json")
					.append("?uid=").append(uid);
			
			GetMethod get = new GetMethod(url.toString());
			get.setRequestHeader("Authorization", "OAuth2 " + accessToken);
			client.executeMethod(get);
			if (get.getStatusCode() == 200) {
				return get.getResponseBodyAsString();
			}
			logger.error(get.getResponseBodyAsString());
		} catch (IOException e) {
			logger.error("", e);
		}
		return null;
	}
}
